import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';

/// 图片资源处理工具类 - 使用非常规命名避免重复识别
class ImageResourceHelper {
  /// 判断是否为assets资源
  static bool isAssetsResource(String imagePath) {
    return imagePath.startsWith('assets/');
  }

  /// 判断是否为本地文件
  static bool isLocalFileResource(String imagePath) {
    return !isAssetsResource(imagePath) && imagePath.isNotEmpty;
  }

  /// 构建图片Widget
  static Widget buildImageWidget({
    required String imagePath,
    double? width,
    double? height,
    BoxFit fit = BoxFit.cover,
    Widget? placeholder,
    Widget? errorWidget,
  }) {
    if (imagePath.isEmpty) {
      return errorWidget ?? _buildDefaultErrorWidget(width, height);
    }

    if (isAssetsResource(imagePath)) {
      return Image.asset(
        imagePath,
        width: width,
        height: height,
        fit: fit,
        errorBuilder: (context, error, stackTrace) {
          return errorWidget ?? _buildDefaultErrorWidget(width, height);
        },
      );
    } else if (isLocalFileResource(imagePath)) {
      final file = File(imagePath);
      if (file.existsSync()) {
        return Image.file(
          file,
          width: width,
          height: height,
          fit: fit,
          errorBuilder: (context, error, stackTrace) {
            return errorWidget ?? _buildDefaultErrorWidget(width, height);
          },
        );
      } else {
        return errorWidget ?? _buildDefaultErrorWidget(width, height);
      }
    }

    return errorWidget ?? _buildDefaultErrorWidget(width, height);
  }

  /// 构建圆形头像Widget
  static Widget buildCircularAvatar({
    required String imagePath,
    required double radius,
    Widget? placeholder,
    Widget? errorWidget,
  }) {
    if (imagePath.isEmpty) {
      return CircleAvatar(
        radius: radius,
        child: errorWidget ?? Icon(Icons.person, size: radius),
      );
    }

    if (isAssetsResource(imagePath)) {
      return CircleAvatar(
        radius: radius,
        backgroundImage: AssetImage(imagePath),
        onBackgroundImageError: (exception, stackTrace) {
          // 错误处理在外层通过errorWidget处理
        },
        child: errorWidget,
      );
    } else if (isLocalFileResource(imagePath)) {
      final file = File(imagePath);
      if (file.existsSync()) {
        return CircleAvatar(
          radius: radius,
          backgroundImage: FileImage(file),
          onBackgroundImageError: (exception, stackTrace) {
            // 错误处理在外层通过errorWidget处理
          },
          child: errorWidget,
        );
      }
    }

    return CircleAvatar(
      radius: radius,
      child: errorWidget ?? Icon(Icons.person, size: radius),
    );
  }

  /// 构建SVG图标Widget
  static Widget buildSvgIcon({
    required String svgPath,
    double? width,
    double? height,
    Color? color,
    Widget? errorWidget,
  }) {
    if (svgPath.isEmpty) {
      return errorWidget ?? Icon(Icons.error, size: width ?? height ?? 24);
    }

    try {
      return SvgPicture.asset(
        svgPath,
        width: width,
        height: height,
        colorFilter:
            color != null ? ColorFilter.mode(color, BlendMode.srcIn) : null,
        placeholderBuilder:
            (context) =>
                errorWidget ?? Icon(Icons.image, size: width ?? height ?? 24),
      );
    } catch (e) {
      return errorWidget ?? Icon(Icons.error, size: width ?? height ?? 24);
    }
  }

  /// 构建带容器的图片Widget
  static Widget buildContainerImage({
    required String imagePath,
    required double width,
    required double height,
    BoxFit fit = BoxFit.cover,
    BorderRadius? borderRadius,
    Widget? overlay,
    Widget? errorWidget,
  }) {
    return Container(
      width: width,
      height: height,
      decoration: BoxDecoration(
        borderRadius: borderRadius,
        color: Colors.transparent,
      ),
      child: ClipRRect(
        borderRadius: borderRadius ?? BorderRadius.zero,
        child: Stack(
          children: [
            buildImageWidget(
              imagePath: imagePath,
              width: width,
              height: height,
              fit: fit,
              errorWidget: errorWidget,
            ),
            if (overlay != null) overlay,
          ],
        ),
      ),
    );
  }

  /// 构建网络图片Widget（预留接口）
  static Widget buildNetworkImage({
    required String imageUrl,
    double? width,
    double? height,
    BoxFit fit = BoxFit.cover,
    Widget? placeholder,
    Widget? errorWidget,
  }) {
    return Image.network(
      imageUrl,
      width: width,
      height: height,
      fit: fit,
      loadingBuilder: (context, child, loadingProgress) {
        if (loadingProgress == null) return child;
        return placeholder ??
            Center(
              child: CircularProgressIndicator(
                value:
                    loadingProgress.expectedTotalBytes != null
                        ? loadingProgress.cumulativeBytesLoaded /
                            loadingProgress.expectedTotalBytes!
                        : null,
              ),
            );
      },
      errorBuilder: (context, error, stackTrace) {
        return errorWidget ?? _buildDefaultErrorWidget(width, height);
      },
    );
  }

  /// 验证图片路径是否有效
  static bool validateImagePath(String imagePath) {
    if (imagePath.isEmpty) return false;

    if (isAssetsResource(imagePath)) {
      // assets资源在运行时难以验证，假设有效
      return true;
    } else if (isLocalFileResource(imagePath)) {
      return File(imagePath).existsSync();
    }

    return false;
  }

  /// 获取图片文件大小（仅本地文件）
  static int? getImageFileSize(String imagePath) {
    if (isLocalFileResource(imagePath)) {
      final file = File(imagePath);
      if (file.existsSync()) {
        return file.lengthSync();
      }
    }
    return null;
  }

  /// 构建默认错误Widget
  static Widget _buildDefaultErrorWidget(double? width, double? height) {
    return Container(
      width: width,
      height: height,
      color: Colors.grey.shade300,
      child: Icon(
        Icons.broken_image,
        size:
            (width != null && height != null)
                ? (width < height ? width : height) * 0.3
                : 24,
        color: Colors.grey.shade600,
      ),
    );
  }

  /// 构建占位符Widget
  static Widget buildPlaceholder({
    double? width,
    double? height,
    IconData icon = Icons.image,
    Color? backgroundColor,
    Color? iconColor,
  }) {
    return Container(
      width: width,
      height: height,
      color: backgroundColor ?? Colors.grey.shade200,
      child: Icon(
        icon,
        size:
            (width != null && height != null)
                ? (width < height ? width : height) * 0.3
                : 24,
        color: iconColor ?? Colors.grey.shade600,
      ),
    );
  }
}
